package com.nineclock.attendance.task;

import cn.hutool.core.collection.CollectionUtil;
import com.nineclock.attendance.mapper.AttendGroupMapper;
import com.nineclock.attendance.pojo.AttendGroup;
import com.nineclock.attendance.service.AttendPunchService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysOrganizationFeign;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Component
@Slf4j
public class SendAttendMailTask {

    @Autowired
    AttendGroupMapper attendGroupMapper;

    @Autowired
    SysOrganizationFeign organizationFeign;

    @Autowired
    AttendPunchService attendPunchService;


    @XxlJob("countAttendanceAndSendMail")
    public void countAttendanceAndSendMail() throws MessagingException {
        //1. 获取企业的id集合
        //查询所有的考勤组
        List<AttendGroup> attendGroups = attendGroupMapper.selectList(null);
        //取出考勤中的 企业id
        Set<Long> companyIds = attendGroups.stream().map(attendGroup -> {
            return attendGroup.getCompanyId();
        }).collect(Collectors.toSet());
        if(CollectionUtil.isNotEmpty(companyIds)){
            for (Long companyId : companyIds) {

                //3. 生成excel文件
                String excelPath = attendPunchService.generateExcelReportByCompanyId(companyId);

                //4. 发送邮件（根据企业id获取主管理员的 邮箱地址）
                SysCompanyUserDTO admin = organizationFeign.queryAdminByCompanyId(companyId).getData();

                this.sendMail(admin.getEmail(),excelPath );
            }
        }
    }

    @Autowired
    JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    String from;

    public void sendMail(String adminEmail, String excelPath) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

        messageHelper.setFrom(from); //发送人
        messageHelper.setTo(adminEmail); // 收件人
        messageHelper.setText("本月考勤报表已生成，请查收"); //内容
        messageHelper.setSubject("考勤报表邮件");

        messageHelper.addAttachment("考勤报表.XLSX", new File(excelPath));

        mailSender.send(mimeMessage);
    }
}
